// pages/tabs/tabs.js

import {
  getItineraryInfoByIdForUser, //行程詳情
  postUserItineraryModifyToTreeForUser, //編輯行程
  getUserFavoritePlaceListForPageForUser, //用戶收藏
  getUserFavoriteListAllForUser, //景點分類
  GetPlaceListForPage, //景點列表
  travel_planGetFlightListAll, //查詢航班
  postPlaceAddForUser
} from '../../api/home'
import {
  imageURL
} from '../../../utils/request'
let flightInputTimer = null;

Page({
  data: {
    imageURL: '',
    itinerary_id: '', //我的行程id
    user_favorite_id: '', //我的收藏分类id
    showModal: false, //刪除
    deleteName: '', // 要刪除的地名
    itinerary_item_id: '', //刪除的地點id
    popupVisible: false, //編輯彈框
    dayStart: false, //每天行程開始彈框
    daySetTimeIndex:'',//點擊哪天的行程設置開始時間
    newMinute: '', //游玩分鐘
    day_num:'',//設置游玩分鐘那個景點的天數
    minuteShow: false, //每個景點游玩分鐘彈框
    dayindex: '', //哪一天行程的index
    childIndex: '', //行程下那个景点的index
    locationVisible: false, //我的收藏地點彈框
    selectVisible: false, //地點選擇彈框
    flightVisible: false, //航班彈框
    flightActiveTab: 0, //航班彈框tab
    trainVisible: false, //列車彈框
    trainActiveTab: 0, //列車彈框tab
    portVisible: false, //口岸彈框
    hotelVisible: false, //酒店彈框
    hotelActiveTab: 0, //列車彈框tab
    showTimePopup: false, //日期彈框
    timePopup: false, //出發到達時間彈框
    dayPopup: false, //住宿天數彈框
    goDayPopup: false, //出发天數彈框
    timeActiveTab: 'date', //出發到達攤開tab
    weekOptions: [], // ["6.29 星期二", "6.30 星期三", ...]
    hourOptions: [], // ["00", "01", "02", ...]
    minuteOptions: [], // ["00", "01", "02", ...]
    pickerValue: [0, 0, 0], // 默認選中第0項
    dayValue: [0, 0], // 默認選中第0項
    dayModal: false, //添加地點至彈框
    portModal: false, //添加口岸至彈框
    flightActiveTab: 0, // 當前選中的tab
    //航班
    flightSegments: [{
      departure: '深圳寶安機場',
      departureTime: '',
      destination: '深圳寶安機場',
      arrivalTime: ''
    }],
    // 航班信息数组（tab=1）
    flightInfos: [{
      // departureDate: '',
      flightNumber: 'CX345',
      airline: '',
      departure: '',
      departureTime: '',
      destination: '',
      arrivalTime: '',
      duration: ''
    }],
    // 列車信息（行程段）
    trainSegments: [{
      departure: '深圳北站',
      departureTime: '',
      destination: '深圳北站',
      arrivalTime: ''
    }],
    // 列車信息
    trainInfos: [{
      // departureDate: '',
      trainNumber: 'Z298',
      departure: '深圳北站',
      departureTime: '7:00',
      destination: '深圳北站',
      arrivalTime: '10:05',
      duration: '3小時5分鐘'
    }],
    // 入住信息
    hotelList: [{
        departure: "",
        departureTime: "",
        longitude: "",
        latitude: ""
      } // 初始一个
    ],
    currentHotelIndex: 0, //酒店下標
    // 口岸信息
    portData: {

      destination: '', // 目的地
      arrivalTime: '', // 到達時間
    },
    calendarConfig: {
      chooseAreaMode: true // 開啟範圍選擇模式
    },
    currentField: '', //选择的是哪个模块的时间
    currentIndex: '', //选择的是哪个模块下哪天的
    activeTab: 'date', // 默認打開天數 tab
    dayOptions: Array.from({
      length: 30
    }, (_, i) => i + 1),
    daysIndex: 0,
    selectedDayIndex: 0,
    isScrolling: false, // 是否正在滚动
    selectedDay: '',
    tabs: ['總覽', 'DAY'],
    activeIndex: 0,
    scrollLeft: 0,
    items: [{
        label: '地點',
        icon: '/pages/assets/image/didian.svg'
      },
      {
        label: '口岸',
        icon: '/pages/assets/image/kouan.svg'
      },
      {
        label: '酒店',
        icon: '/pages/assets/image/jiudian.svg'
      },
      // {
      //   label: '列車',
      //   icon: '/pages/assets/image/lieche.svg'
      // },
      // {
      //   label: '航班',
      //   icon: '/pages/assets/image/hangban.svg'
      // },
    ],
    // 地點選擇
    keyword: '',
    places: [{
        id: 1,
        image: '/pages/assets/image/motianlun.jpg',
        name: '維多利亞港',
        desc: '「香港璀璨夜景的最佳觀景點...」',
        selected: false,
      },
      {
        id: 2,
        image: '/pages/assets/image/motianlun.jpg',
        name: '維多利亞港',
        desc: '「香港璀璨夜景的最佳觀景點...」',
        selected: false,
      },
      {
        id: 3,
        image: '/pages/assets/image/motianlun.jpg',
        name: '維多利亞港',
        desc: '「香港璀璨夜景的最佳觀景點...」',
        selected: true,
      },
    ],
    collectKeyword: '',
    collectPlaces: [{
        id: 1,
        image: '/pages/assets/image/motianlun.jpg',
        name: '維多利亞港',
        desc: '「香港璀璨夜景的最佳觀景點...」',
        selected: false,
      },
      {
        id: 2,
        image: '/pages/assets/image/motianlun.jpg',
        name: '維多利亞港',
        desc: '「香港璀璨夜景的最佳觀景點...」',
        selected: false,
      },
      {
        id: 3,
        image: '/pages/assets/image/motianlun.jpg',
        name: '維多利亞港',
        desc: '「香港璀璨夜景的最佳觀景點...」',
        selected: true,
      },
    ],
    addDays: [],
    addPort: ['福田口岸', '羅湖口岸', '皇崗口岸', '深圳灣口岸'],
    portIndex: 0, //口岸index
    days: [],
    //交通選擇
    transportOptions: [{
        label: '公共交通',
        icon: '/pages/assets/image/bus.svg',
        id: 1
      },
      {
        label: '架車',
        icon: '/pages/assets/image/car.svg',
        id: 2

      },
      {
        label: '走路',
        icon: '/pages/assets/image/go.svg',
        id: 3

      }
    ],
    selectedTransportId: '',
    //時間選擇
    hours: Array.from({
      length: 24
    }, (_, i) => (i < 10 ? '0' + i : '' + i)),
    minutes: Array.from({
      length: 60
    }, (_, i) => (i < 10 ? '0' + i : '' + i)),
    startValue: ['08', '00'],
    start_time: '',
    endValue: ['20', '00'],
    end_time: '',
    itineraryDetail: {},
    // 分類
    collectTabs: [],
    rows: 10,
    page: 1,
    loadingMore: false,
    noMore: false,
  },
  async onLoad(e) {
    this.setData({
      imageURL,
      itinerary_id: e.itinerary_id
    })
    this.getData()
    this.getType()
    this.getCollect()
    this.getList()
    this.initPickerData();
  },
  // 滚动开始
  onDayPickerStart() {
    this.setData({
      isScrolling: true
    })
  },

  // 滚动结束
  onDayPickerEnd() {
    this.setData({
      isScrolling: false
    })
  },
  keyInput(e) {
    this.setData({
      keyword: e.detail.value,
    })
    if (e.detail.value == '') {
      this.setData({
        page: 1,
        noMore: false
      });
      this.getList(false);
    }
  },
  collectInput(e) {

    this.setData({
      collectKeyword: e.detail.value
    })
    if (e.detail.value == '') {
      this.getCollect()
    }
    console.log(this.data.collectKeyword);
  },
  // 用户点击键盘“完成/搜索”时触发
  onCollectConfirm(e) {
    const keyword = this.data.collectKeyword
    if (keyword) {
      this.getCollect()
    }
  },
  onkeyConfirm(e) {
    const keyword = this.data.keyword
    if (keyword) {
      this.setData({
        page: 1,
        noMore: false
      });
      this.getList(false);
    }
  },
  //地点列表
  async getList(isLoadMore = false) {
    if (this.data.noMore || this.data.loadingMore) return; // 避免重复加载

    this.setData({
      loadingMore: true
    });

    const res = await GetPlaceListForPage({
      page: this.data.page,
      rows: this.data.rows,
      keyword: this.data.keyword || '',
      place_category_id: '',
      is_hot: ''
    });

    let newPlaces = this.markSelected(res.data.list, this.data.itineraryDetail);

    // 如果是上拉加载，拼接数据；否则覆盖
    let places = isLoadMore ?
      this.data.places.concat(newPlaces) :
      newPlaces;

    this.setData({
      places,
      loadingMore: false,
      noMore: newPlaces.length < this.data.rows // 如果不足一页，就没有更多了
    });
  },
  // 触底加载更多
  loadMore() {
    if (this.data.noMore) return;
    this.setData({
      page: this.data.page + 1
    });
    this.getList(true);
  },
  //收藏列表
  async getCollect() {
    const res = await getUserFavoritePlaceListForPageForUser({
      page: 1,
      rows: 9999,
      keyword: this.data.collectKeyword,
      user_favorite_id: this.data.user_favorite_id,
    });

    const collectPlaces = this.markSelected(res.data.list, this.data.itineraryDetail);
    this.setData({
      collectPlaces
    });
  },
  //收藏分类
  async getType() {
    const res = await getUserFavoriteListAllForUser()
    const categories = Array.isArray(res.data.list) ? res.data.list : []

    // 在最前面加一个 "全部"
    const tabs = [{
      id: '',
      name: '全部'
    }, ...categories]
    this.setData({
      collectTabs: tabs
    })
  },
  //编辑详情
  async getData() {
    const res = await getItineraryInfoByIdForUser({
      itinerary_id: this.data.itinerary_id
    })
    const days = Array.from({
      length: res.data.info.number_day
    }, (_, i) => `DAY ${i + 1}`)
    this.setData({
      addDays: days,
      itineraryDetail: res.data,
      selectedTransportId: res.data.info.transportation
    })
  },
  //对比方法
  markSelected(list, itineraryDetail) {
    // 收集所有已选景点 id
    const selectedIds = [];
    itineraryDetail.list_item?.forEach(day => {
      day.child.forEach(place => {
        selectedIds.push(place.place_id);
      });
    });

    // 遍历列表，勾选
    return list.map(item => ({
      ...item,
      selected: selectedIds.includes(item.place_id)
    }));
  },

  // 入住天數切換選中狀態
  toggleDay(e) {
    const index = e.currentTarget.dataset.index
    const days = this.data.itineraryDetail.list_item
    console.log(days);
    days[index].selected = !days[index].selected
    this.setData({
      'itineraryDetail.list_item': days
    })
  },
  // 选择入住确认
  hotelDayClick() {
    const days = this.data.itineraryDetail.list_item; // 所有天
    const selectedDays = days
      .filter(item => item.selected)
      .map(item => `DAY ${item.day_num}`); // 拼接字符串

    if (!selectedDays.length) {
      wx.showToast({
        title: '请先选择天数',
        icon: 'none'
      });
      return;
    }

    // 拼接成字符串，用 / 分隔
    const dayStr = selectedDays.join(' / ');

    let hotelList = this.data.hotelList;
    const index = this.data.currentHotelIndex; // 使用当前索引
    if (index !== undefined && hotelList[index]) {
      hotelList[index].departureTime = dayStr;
      this.setData({
        hotelList,
        dayPopup: false // 关闭弹框
      });
    }

    // 清除选中状态
    const resetDays = days.map(d => ({
      ...d,
      selected: false
    }));
    this.setData({
      'itineraryDetail.list_item': resetDays,
      dayPopup: false
    });
  },
  // 完成编辑入住酒店
  async hotelOkClick() {
    const {
      itineraryDetail,
      hotelList
    } = this.data;
    // 校验 hotelList 是否有空值
    for (let i = 0; i < hotelList.length; i++) {
      const hotel = hotelList[i];
      if (!hotel.departure || !hotel.departureTime) {
        wx.showToast({
          title: `第 ${i + 1} 条住宿信息未填写完整`,
          icon: 'none'
        });
        return; // 发现空值，直接退出函数
      }
    }
    // 遍历 hotelList，把每条的 departureTime 解析成选中的天数数组
    hotelList.forEach(hotel => {
      if (!hotel.departureTime) return;

      // departureTime 格式: "DAY 1 / DAY 2"
      const selectedDays = hotel.departureTime.split(' / ').map(d => parseInt(d.replace('DAY ', '')));

      selectedDays.forEach(dayNum => {
        // 找到对应的 list_item
        const listItem = itineraryDetail.list_item.find(item => item.day_num === dayNum);
        if (listItem) {
          // 确保 child 数组存在
          if (!listItem.child) listItem.child = [];
          // 在 child 前面插入住宿信息
          listItem.child.unshift({
            type: 5,
            start_time: '00:00',
            end_time: '00:00',
            title: hotel.departure,
            latitude: hotel.latitude || null, // 纬度
            longitude: hotel.longitude || null // 经度
          });
        }
      });
    });

    // 组织提交数据
    const data = {
      itinerary_id: itineraryDetail.info.itinerary_id,
      itinerary_catalog_id: itineraryDetail.info.itinerary_catalog_id,
      name: itineraryDetail.info.name,
      number_day: itineraryDetail.info.number_day,
      transportation: itineraryDetail.info.transportation,
      start_time: itineraryDetail.info.start_time,
      end_time: itineraryDetail.info.end_time,
      img_url_cover: itineraryDetail.info.img_url_cover,
      list_item: itineraryDetail.list_item,
    };

    // 提交接口
    const res = await postUserItineraryModifyToTreeForUser(data);
    wx.showToast({
      title: '酒店已添加',
    })
    // 清空弹框和住宿输入
    this.setData({
      hotelVisible: false,
      hotelList: [{
        departure: '',
        departureTime: ''
      }],
    });
    this.getData()
  },
  // 确认出发天数
  goDay(e) {
    const index = e.currentTarget.dataset.index;
    const days = this.data.itineraryDetail.list_item.map((item, i) => {
      return {
        ...item,
        selected: i === index // 只有点击的那个是 true
      }
    });
    this.setData({
      'itineraryDetail.list_item': days
    });
  },
  // 出发天數確認按鈕事件
  selectDayClick() {
    const {
      itineraryDetail,
      currentField,
      currentIndex
    } = this.data;

    // 找到选中的天数
    const selectedDay = itineraryDetail.list_item.find(d => d.selected);
    if (!selectedDay) {
      wx.showToast({
        title: '請選擇天數',
        icon: 'none'
      });
      return;
    }

    // 拼接一个时间（比如用 day_num + ":00:00" 占位，也可以后面再弹 picker）
    const timeValue = `DAY ${selectedDay.day_num}`;

    // 根据 currentField 更新数据
    if (currentField.startsWith('flightSegments')) {
      const key = currentField.includes('DepartureTime') ? 'departureTime' : 'arrivalTime';
      const flightSegments = this.data.flightSegments;
      flightSegments[currentIndex][key] = timeValue;
      this.setData({
        flightSegments
      });
    } else if (currentField.startsWith('trainSegments')) {
      const key = currentField.includes('DepartureTime') ? 'departureTime' : 'arrivalTime';
      const trainSegments = this.data.trainSegments;
      trainSegments[currentIndex][key] = timeValue;
      this.setData({
        trainSegments
      });
    } else if (currentField.startsWith('portData')) {
      const key = currentField.includes('DepartureTime') ? 'departureTime' : 'arrivalTime';
      const portData = this.data.portData;
      portData[key] = timeValue;
      this.setData({
        portData
      });
    }

    this.setData({
      dayPopup: false,
      goDayPopup: false,
      currentField: null,
      currentIndex: null,
    });
  },

  // 收藏列表点击选择
  toggleCollectSelect(e) {
    const id = e.currentTarget.dataset.id;
    let selectedPlace = null;

    const newCollectPlaces = this.data.collectPlaces.map(p => {
      if (p.place_id === id) {
        p.selected = !p.selected;
        if (p.selected) selectedPlace = p;
      }
      return p;
    });
    console.log(newCollectPlaces);
    this.setData({
      collectPlaces: newCollectPlaces,
    });

    if (selectedPlace) {
      const selectData = {
        "place_id": selectedPlace.place_id,
        "title": selectedPlace.place_name,
        "type": 11,

        "start_time": "00:00:00",
        "end_time": "00:00:00"
      }
      // 打开选择天数弹窗
      this.setData({
        currentSelectedPlace: selectData,
        dayModal: true
      });
    } else {
      // 取消选择，从行程里删除
      this.removePlaceFromList(id);
    }
  },

  //選擇地點
  toggleSelect(e) {
    const id = e.currentTarget.dataset.id;
    let selectedPlace = null;

    const newPlaces = this.data.places.map(p => {
      if (p.place_id === id) {
        p.selected = !p.selected;
        if (p.selected) selectedPlace = p;
      }
      return p;
    });

    this.setData({
      places: newPlaces,
    });

    if (selectedPlace) {
      // 打开选择天数弹窗
      const selectData = {
        "place_id": selectedPlace.place_id,
        "title": selectedPlace.name,
        "type": 11,
        "start_time": "00:00:00",
        "end_time": "00:00:00"
      }
      this.setData({
        currentSelectedPlace: selectData,
        dayModal: true
      });
    } else {
      // 如果取消选择，从 itineraryDetail 中删除
      this.removePlaceFromList(id);
    }
  },
  // 确认选择
  confirmSelect() {
    if (this.data.isScrolling) {
      wx.showToast({
        title: '請等待滾動停止',
        icon: 'none'
      })
      return
    }
    const {
      currentSelectedPlace,
      selectedDayIndex,
      itineraryDetail
    } = this.data;
    if (!currentSelectedPlace) return;

    let dayList = itineraryDetail.list_item || [];

    // 根据 day_num 查找对应天（day_num 从 1 开始）
    let day = dayList.find(d => d.day_num === selectedDayIndex + 1);

    if (!day) {
      // 如果没有找到对应天，则新建
      day = {
        day_num: selectedDayIndex + 1,
        child: [],
        theme: ''
      };
      dayList.push(day); // 注意这里 push 到数组，而不是直接用索引
    }

    // 添加景点
    day.child.push({
      ...currentSelectedPlace,
      start_time: "00:00:00",
      end_time: "00:00:00"
    });

    // 更新数据
    this.setData({
      'itineraryDetail.list_item': dayList,
      dayModal: false,
      currentSelectedPlace: null
    });
  },
  // confirmSelect() {
  //   const {
  //     currentSelectedPlace,
  //     selectedDayIndex,
  //     itineraryDetail
  //   } = this.data;
  //   if (!currentSelectedPlace) return;

  //   // 确保 list_item 存在
  //   let dayList = itineraryDetail.list_item || [];

  //   // 如果选中的 day 不存在，先初始化
  //   if (!dayList[selectedDayIndex]) {
  //     dayList[selectedDayIndex] = {
  //       day_num: selectedDayIndex + 1,
  //       child: [],
  //       theme: ''
  //     };
  //   }

  //   const day = dayList[selectedDayIndex];

  //   // 确保 child 存在
  //   if (!day.child) day.child = [];

  //   // 添加景点
  //   day.child.push({
  //     ...currentSelectedPlace,
  //     start_time: "00:00:00",
  //     end_time: "00:00:00"
  //   });

  //   // 更新数据
  //   this.setData({
  //     'itineraryDetail.list_item': dayList,
  //     dayModal: false,
  //     currentSelectedPlace: null
  //   });
  // },

  // 删除逻辑（取消选择）
  removePlaceFromList(place_id) {
    const {
      itineraryDetail
    } = this.data;
    itineraryDetail.list_item.forEach(day => {
      day.child = day.child.filter(c => c.place_id !== place_id);
    });
    console.log(itineraryDetail);
    this.setData({
      itineraryDetail
    });
  },
  //打开添加列表選擇弹框
  scrollClick(e) {
    const index = e.currentTarget.dataset.index
    if (index == 0) {
      const {
        itineraryDetail
      } = this.data;
      this.originalDetail = JSON.parse(JSON.stringify(itineraryDetail)); // 深拷贝一份
      this.setData({
        selectVisible: true
      })
    } else if (index == 1) {
      this.setData({
        portVisible: true
      })
    } else if (index == 2) {
      this.setData({
        hotelVisible: true
      })
    } else if (index == 3) {
      this.setData({
        trainVisible: true
      })
    } else if (index == 4) {
      this.setData({
        flightVisible: true
      })
    }

  },
  // 添加航程段
  addSegment() {
    let list = this.data.flightSegments;
    list.push({
      departure: '',
      departureTime: '',
      destination: '',
      arrivalTime: '',
      title: `航班`
    });
    this.setData({
      flightSegments: list
    });
  },
  // 删除航程
  delSegment(e) {
    const index = e.currentTarget.dataset.index; // 获取要删除的索引
    let list = this.data.flightSegments;

    if (list.length <= 1) {
      wx.showToast({
        title: '至少保留一個航程',
        icon: 'none'
      });
      return;
    }

    list.splice(index, 1); // 删除对应项
    this.setData({
      flightSegments: list
    });
  },
  //打开收藏
  goToFavorites() {
    this.setData({
      selectVisible: false,
      locationVisible: true,
    })
  },
  //日期彈框tab
  switchTabTime(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },
  // 航班tab
  flightSwitchTab(e) {
    const index = Number(e.currentTarget.dataset.index);
    this.setData({
      flightActiveTab: index
    });
  },
  // 航班輸入事件
  onSegmentInput(e) {
    const {
      index,
      field
    } = e.currentTarget.dataset;
    let list = this.data.flightSegments;
    list[index][field] = e.detail.value;
    this.setData({
      flightSegments: list
    });
    console.log(list);
  },

  onFlightInfoInput(e) {
    const {
      index,
      field
    } = e.currentTarget.dataset;
    let list = this.data.flightInfos;

    // 确保当前对象存在
    if (!list[index]) list[index] = {};

    // 更新输入值
    list[index][field] = e.detail.value;
    this.setData({
      flightInfos: list
    });

    // 调用防抖搜索
    this.getFlightList(index, e.detail.value);
  },
  async getFlightList(index, value) {
    // 清除上一次的定时器
    if (!this.flightInputTimers) this.flightInputTimers = [];
    if (this.flightInputTimers[index]) clearTimeout(this.flightInputTimers[index]);

    this.flightInputTimers[index] = setTimeout(async () => {
      const res = await travel_planGetFlightListAll({
        number: value
      });
      console.log("接口返回", res);

      if (res && res.data && res.data.list && res.data.list.length) {
        const list = this.data.flightInfos;

        // 取第一条接口返回数据映射到对应索引
        const flightData = res.data.list[0]; // 如果接口返回多条，也可以做选择
        list[index] = {
          ...list[index], // 保留用户输入的字段
          flightNumber: value, // 保留用户输入
          airline: '', // 如果接口返回航空公司可以填 flightData.airline
          departure: flightData.departure,
          departureTime: flightData.scheduled_departure,
          destination: flightData.destination,
          arrivalTime: flightData.scheduled_arrival,
          duration: flightData.flight_time,
          title: `航班信息`
        };

        this.setData({
          flightInfos: list
        });
      }
    }, 1000);
  },
  // 添加一个住宿项
  addItem() {
    let list = this.data.hotelList;
    list.push({
      departure: "",
      departureTime: "",
      longitude: "",
      latitude: "",
      title: `住宿`
    });
    this.setData({
      hotelList: list
    });
  },
  // 删除住宿项
  delItem(e) {
    const index = e.currentTarget.dataset.index;
    let list = this.data.hotelList;

    if (list.length <= 1) {
      wx.showToast({
        title: '至少保留一个住宿',
        icon: 'none'
      });
      return;
    }

    list.splice(index, 1); // 删除对应项
    this.setData({
      hotelList: list
    });
  },
  // 基本信息输入
  onTrainSegmentInput(e) {
    const {
      index,
      field
    } = e.currentTarget.dataset;
    let list = this.data.trainSegments;
    list[index][field] = e.detail.value;
    this.setData({
      trainSegments: list
    });
  },
  // 列車信息输入
  onTrainInfoInput(e) {
    const {
      index,
      field
    } = e.currentTarget.dataset;
    let list = this.data.trainInfos;
    list[index][field] = e.detail.value;
    this.setData({
      trainInfos: list
    });
    console.log(list);
  },
  // 添加行程段
  addTrainSegment() {
    let list = this.data.trainSegments;
    list.push({
      departure: '',
      departureTime: '',
      destination: '',
      arrivalTime: '',
      title: '列车'
    });
    this.setData({
      trainSegments: list
    });
  },

  // 刪除行程段
  delTrainSegment(e) {
    const index = e.currentTarget.dataset.index; // 拿到點擊刪除的 index
    let list = [...this.data.trainSegments]; // 複製數據

    if (list.length <= 1) {
      wx.showToast({
        title: '至少保留一個行程段',
        icon: 'none'
      });
      return;
    }

    list.splice(index, 1); // 刪除對應項
    this.setData({
      trainSegments: list
    });
  },
  // 添加列車信息
  addTrainInfo() {
    let list = this.data.trainInfos;
    list.push({
      departureDate: '',
      trainNumber: '',
      departure: '',
      departureTime: '',
      destination: '',
      arrivalTime: '',
      duration: '',
      title: '列车信息'
    });
    this.setData({
      trainInfos: list
    });
  },
  // 删除列车信息
  delTrainInfo(e) {
    const index = e.currentTarget.dataset.index;
    let list = this.data.trainInfos;

    if (list.length <= 1) {
      wx.showToast({
        title: '至少保留一个列车信息',
        icon: 'none'
      });
      return;
    }

    list.splice(index, 1); // 删除对应项
    this.setData({
      trainInfos: list
    });
  },

  // 添加航班信息
  addFlightInfo() {
    let list = this.data.flightInfos;
    list.push({
      departureDate: '',
      flightNumber: '',
      airline: '',
      departure: '',
      departureTime: '',
      destination: '',
      arrivalTime: '',
      duration: '',
      title: `航班信息`
    });
    this.setData({
      flightInfos: list
    });
  },
  // 删除航班信息
  delFlightInfo(e) {
    const index = e.currentTarget.dataset.index;
    let list = this.data.flightInfos;

    if (list.length <= 1) {
      wx.showToast({
        title: '至少保留一个航班信息',
        icon: 'none'
      });
      return;
    }

    list.splice(index, 1); // 删除对应项
    this.setData({
      flightInfos: list
    });
  },

  // 输入住宿点
  onHotelInput(e) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    let list = this.data.hotelList;
    list[index].departure = value;
    this.setData({
      hotelList: list
    });
  },
  chooseLocation(e) {
    const index = e.currentTarget.dataset.index;

    wx.chooseLocation({
      success: (res) => {
        console.log("选中的地点：", res);

        let list = this.data.hotelList;
        list[index].departure = res.name || res.address; // 地点名称
        list[index].latitude = res.latitude; // 纬度
        list[index].longitude = res.longitude; // 经度

        this.setData({
          hotelList: list
        });
        console.log(this.data.hotelList);
      },
      fail: (err) => {
        console.log("用户未选择地点", err);
      }
    });
  },
  chooseLocation2(e) {
  
    wx.chooseLocation({
      success:  (res) => {
        console.log("选中的地点：", res);
        if(res.latitude){
          this.addJd(res)
        }
      },
      fail: (err) => {
        console.log("用户未选择地点", err);
      }
    });
  },
  async addJd(res){
    const info = await postPlaceAddForUser({
      "name": res.name,
      "address": res.address,
      "longitude": res.longitude,
      "latitude": res.latitude
    })
       await this.getList()
       this.getCollect()
        wx.showToast({
          title: '添加成功',
        })
  },
  minuteShowClick(e) {
    const day_num = e.currentTarget.dataset.day_num;
    const itinerary_item_id = e.currentTarget.dataset.itinerary_item_id;
    console.log(day_num,itinerary_item_id);
    this.setData({
      day_num,
      itinerary_item_id,
      minuteShow: true
    })
  },
  onInputminute(e){
    this.setData({
      newMinute:e.detail.value
    })
  },
  //游玩時間
  async confirmAddMinute() {
    const { itinerary_item_id, day_num, itineraryDetail, newMinute } = this.data
  
    // 🔹 遍歷 list_item
    itineraryDetail.list_item.forEach(dayItem => {
      if (dayItem.day_num === day_num && Array.isArray(dayItem.child)) {
        dayItem.child.forEach(childItem => {
          if (childItem.itinerary_item_id === itinerary_item_id) {
            childItem.minute = newMinute  // ✅ 更新 minute
          }
        })
      }
    })
  
    // 🔹 調接口保存
    const data = {
      itinerary_id: itineraryDetail.info.itinerary_id,
      itinerary_catalog_id: itineraryDetail.info.itinerary_catalog_id,
      name: itineraryDetail.info.name,
      number_day: itineraryDetail.info.number_day,
      transportation: itineraryDetail.info.transportation,
      start_time: itineraryDetail.info.start_time,
      end_time: itineraryDetail.info.end_time,
      img_url_cover: itineraryDetail.info.img_url_cover,
      list_item: itineraryDetail.list_item,
    }
  
    await postUserItineraryModifyToTreeForUser(data)
  
    wx.showToast({
      title: '游玩時間已添加',
      icon: 'success'
    })
  
    this.getData()
    this.setData({
      minuteShow: false,
      newMinute: ''
    })
  },
  chooseDayPop(e) {
    const index = e.currentTarget.dataset.index
    const start_time_no_second = e.currentTarget.dataset.start_time_no_second
    let dayValue = []
    if (start_time_no_second) {
      // "01:00" -> ["01","00"] -> [1,0]
      const [hour, minute] = start_time_no_second.split(':')
      dayValue = [parseInt(hour, 10), parseInt(minute, 10)]
    }
    this.setData({
      daySetTimeIndex:index,
      dayStart: true,
      dayValue
    })
  },
  async dayStartOk() {
    if (this.data.isScrolling) {
      wx.showToast({
        title: '請等待滾動停止',
        icon: 'none'
      })
      return
    }
  
    const { itineraryDetail, daySetTimeIndex, dayValue } = this.data
  
    // 轉換 dayValue => "HH:MM"
    // dayValue 可能是 [7, 9] 或者 [7.9]，需要處理
    let hour = String(dayValue[0]).padStart(2, '0')
    let minute = String(dayValue[1]).padStart(2, '0')
    const formattedTime = `${hour}:${minute}`
  
    // 賦值給 list_item 對應的 start_time_no_second
    if (
      itineraryDetail.list_item &&
      itineraryDetail.list_item[daySetTimeIndex]
    ) {
      itineraryDetail.list_item[daySetTimeIndex].start_time_no_second =
        formattedTime
        itineraryDetail.list_item[daySetTimeIndex].start_time =
        formattedTime+":"+"00"
    }
  
    // 5. 調接口保存
    const data = {
      itinerary_id: itineraryDetail.info.itinerary_id,
      itinerary_catalog_id: itineraryDetail.info.itinerary_catalog_id,
      name: itineraryDetail.info.name,
      number_day: itineraryDetail.info.number_day,
      transportation: itineraryDetail.info.transportation,
      start_time: itineraryDetail.info.start_time,
      end_time: itineraryDetail.info.end_time,
      img_url_cover: itineraryDetail.info.img_url_cover,
      list_item: itineraryDetail.list_item,
    }
  
    await postUserItineraryModifyToTreeForUser(data)
  
    wx.showToast({
      title: '添加成功',
      icon: 'success'
    })
  
    this.getData()
    this.setData({
      dayStart: false
    })
  },
  // 完成添加列車（严格校验每一项字段）
  async trainOkClick() {
    const {
      itineraryDetail = {}, trainSegments = [], trainInfos = []
    } = this.data;

    // 必须有至少一条行程段
    if (!Array.isArray(trainSegments) || trainSegments.length === 0) {
      wx.showToast({
        title: '请完整填写列车信息',
        icon: 'none'
      });
      return;
    }

    // 段数与车次号数量必须一致
    if (!Array.isArray(trainInfos) || trainInfos.length !== trainSegments.length) {
      wx.showToast({
        title: '请为每个行程段填写车次号',
        icon: 'none'
      });
      return;
    }

    // 逐条验证每个字段：departure/departureTime/destination/arrivalTime/trainNumber
    for (let i = 0; i < trainSegments.length; i++) {
      const seg = trainSegments[i] || {};
      const info = trainInfos[i] || {};
      const missing = !seg.departure ||
        !seg.departureTime ||
        !seg.destination ||
        !seg.arrivalTime ||
        !info.trainNumber ||
        !info.trainNumber.toString().trim();

      if (missing) {
        wx.showToast({
          title: '请完整填写列车信息',
          icon: 'none'
        });
        return;
      }
    }

    // 确保 list_item 存在并且每天 child 也存在
    itineraryDetail.list_item = itineraryDetail.list_item || [];
    itineraryDetail.list_item.forEach(day => {
      if (!Array.isArray(day.child)) day.child = [];
    });

    // 遍历每个行程段并插入到对应天（unshift 到最前面）
    trainSegments.forEach((segment, idx) => {
      const {
        departure,
        departureTime,
        destination,
        arrivalTime
      } = segment;
      const trainNumber = trainInfos[idx].trainNumber.trim();
      const departureTitle = `${departure} ${trainNumber}`;
      const destinationTitle = `${destination} ${trainNumber}`;

      if (departureTime && arrivalTime && departureTime === arrivalTime) {
        // 同一天：只插入目的地（并拼接车次）
        const day = itineraryDetail.list_item.find(d => `DAY ${d.day_num}` === departureTime);
        if (day) {
          day.child.unshift({
            type: 2,
            title: destinationTitle,
            start_time: "00:00:00",
            end_time: "00:00:00"
          });
        }
      } else {
        // 出發天
        const depDay = itineraryDetail.list_item.find(d => `DAY ${d.day_num}` === departureTime);
        if (depDay) {
          depDay.child.unshift({
            type: 2,
            title: departureTitle,
            start_time: "00:00:00",
            end_time: "00:00:00"
          });
        }

        // 到達天
        const arrDay = itineraryDetail.list_item.find(d => `DAY ${d.day_num}` === arrivalTime);
        if (arrDay) {
          arrDay.child.unshift({
            type: 2,
            title: destinationTitle,
            start_time: "00:00:00",
            end_time: "00:00:00"
          });
        }
      }
    });

    // 调接口保存
    const data = {
      itinerary_id: itineraryDetail.info.itinerary_id,
      itinerary_catalog_id: itineraryDetail.info.itinerary_catalog_id,
      name: itineraryDetail.info.name,
      number_day: itineraryDetail.info.number_day,
      transportation: itineraryDetail.info.transportation,
      start_time: itineraryDetail.info.start_time,
      end_time: itineraryDetail.info.end_time,
      img_url_cover: itineraryDetail.info.img_url_cover,
      list_item: itineraryDetail.list_item,
    };

    try {
      await postUserItineraryModifyToTreeForUser(data);
      wx.showToast({
        title: '列车已添加',
        icon: 'success'
      });
      // 🔥 保存成功后清空原始数据
      this.setData({
        trainVisible: false,
        trainSegments: [{
          departure: '',
          departureTime: '',
          destination: '',
          arrivalTime: '',
        }],
        trainInfos: [{
          trainNumber: ''
        }]
      });
      this.getData()
    } catch (err) {
      console.error(err);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    }
  },
  // 完成添加航班
  async flightOkClick() {
    const {
      itineraryDetail,
      flightSegments,
      flightInfos
    } = this.data;

    // 1. 校驗數量：段數和航班信息一致
    if (flightSegments.length !== flightInfos.length) {
      wx.showToast({
        title: '請為每個航程段填寫航班號',
        icon: 'none'
      });
      return;
    }

    // 2. 校驗每個航班號是否填寫
    const emptyIndex = flightInfos.findIndex(info => !info.flightNumber || !info.flightNumber.trim());
    if (emptyIndex !== -1) {
      wx.showToast({
        title: `請填寫第 ${emptyIndex + 1} 個航班號`,
        icon: 'none'
      });
      return;
    }

    // 3. 確保每一天都有 child
    itineraryDetail.list_item.forEach(day => {
      if (!day.child) day.child = [];
    });

    // 4. 遍歷每個航程段，根據 day_num 插入數據
    flightSegments.forEach((segment, idx) => {
      const {
        departure,
        departureTime,
        destination,
        arrivalTime
      } = segment;
      const flightNumber = flightInfos[idx].flightNumber;

      const departureTitle = `${departure} ${flightNumber}`;
      const destinationTitle = `${destination} ${flightNumber}`;

      if (departureTime && arrivalTime && departureTime === arrivalTime) {
        // 出發和到達同一天，只插入目的地
        const day = itineraryDetail.list_item.find(d => `DAY ${d.day_num}` === departureTime);
        if (day) {
          day.child.unshift({
            type: 3, // 航班標識，自定義
            title: destinationTitle,
            start_time: "00:00:00",
            end_time: "00:00:00"
          });
        }
      } else {
        // 出發天
        const depDay = itineraryDetail.list_item.find(d => `DAY ${d.day_num}` === departureTime);
        if (depDay) {
          depDay.child.unshift({
            type: 3,
            title: departureTitle,
            start_time: "00:00:00",
            end_time: "00:00:00"
          });
        }

        // 到達天
        const arrDay = itineraryDetail.list_item.find(d => `DAY ${d.day_num}` === arrivalTime);
        if (arrDay) {
          arrDay.child.unshift({
            type: 3,
            title: destinationTitle,
            start_time: "00:00:00",
            end_time: "00:00:00"
          });
        }
      }
    });

    // 5. 調接口保存
    const data = {
      itinerary_id: itineraryDetail.info.itinerary_id,
      itinerary_catalog_id: itineraryDetail.info.itinerary_catalog_id,
      name: itineraryDetail.info.name,
      number_day: itineraryDetail.info.number_day,
      transportation: itineraryDetail.info.transportation,
      start_time: itineraryDetail.info.start_time,
      end_time: itineraryDetail.info.end_time,
      img_url_cover: itineraryDetail.info.img_url_cover,
      list_item: itineraryDetail.list_item,
    };

    await postUserItineraryModifyToTreeForUser(data);

    wx.showToast({
      title: '航班已添加',
      icon: 'success'
    });
    this.getData()
    // 清空數據，關閉彈框
    this.setData({
      flightVisible: false,
      flightSegments: [{
        departure: '',
        departureTime: '',
        destination: '',
        arrivalTime: '',
        title: '航程段'
      }],
      flightInfos: [{
        flightNumber: ''
      }]
    });
  },

  // 完成添加口岸
  async portOkClick() {
    const {
      itineraryDetail,
      portData
    } = this.data;

    const arrivalDay = portData.arrivalTime; // 已选的到达天数 (比如 "DAY 2")

    // 🔹 判斷是否有填寫必要信息（目的地 + 到達天數）
    if (!portData.destination || !arrivalDay) {
      wx.showToast({
        title: '請完整填寫口岸信息',
        icon: 'none'
      });
      return;
    }

    // 確保 child 不為空
    itineraryDetail.list_item.forEach(day => {
      if (!day.child) day.child = [];
    });

    // 到达天添加口岸信息
    const arrDay = itineraryDetail.list_item.find(
      d => `DAY ${d.day_num}` === arrivalDay
    );
    if (arrDay) {
      arrDay.child.unshift({
        type: 4,
        title: portData.destination,
        start_time: "00:00:00",
        end_time: "00:00:00"
      });
    }

    // 🔹 调接口保存
    const data = {
      itinerary_id: itineraryDetail.info.itinerary_id,
      itinerary_catalog_id: itineraryDetail.info.itinerary_catalog_id,
      name: itineraryDetail.info.name,
      number_day: itineraryDetail.info.number_day,
      transportation: itineraryDetail.info.transportation,
      start_time: itineraryDetail.info.start_time,
      end_time: itineraryDetail.info.end_time,
      img_url_cover: itineraryDetail.info.img_url_cover,
      list_item: itineraryDetail.list_item,
    };

    await postUserItineraryModifyToTreeForUser(data);

    wx.showToast({
      title: '口岸已添加',
      icon: 'success'
    });

    this.setData({
      portVisible: false,
      portData: {
        destination: '',
        arrivalTime: '',
      },
    });

    this.getData();
  },


  // 出发时间
  selectDepartureTime(e) {
    const item = e.currentTarget.dataset.item; // 比如 "portDataDepartureTime"
    const index = e.currentTarget.dataset.index; // 如果是数组的，就传索引
    this.setData({
      goDayPopup: true,
      currentField: item, // 保存是哪个字段
      currentIndex: index, // 保存索引（航班、列车才需要）
    });
  },

  // 到达时间
  selectArrivalTime(e) {
    const item = e.currentTarget.dataset.item;
    const index = e.currentTarget.dataset.index;
    this.setData({
      goDayPopup: true,
      currentField: item,
      currentIndex: index,
    });
  },
  portShow() {
    this.setData({
      portModal: true
    })
  },
  // 住宿天數彈框
  selectHotelDay(e) {
    const index = e.currentTarget.dataset.index; // 当前点击的住宿索引
    this.setData({
      currentHotelIndex: index,
      dayPopup: true
    });
  },
  openPopup() {
    this.setData({
      showTimePopup: true
    });
  },

  closePopup() {
    this.setData({
      showTimePopup: false,
      minuteShow: false,
      dayStart:false
    });
  },

  onportPickerChange(e) {
    const index = e.detail.value[0]
    this.setData({
      // selectedDayIndex: e.detail.value[0]
      portIndex: index
    });
  },
  portClick() {
    this.setData({
      'portData.destination': this.data.addPort[this.data.portIndex],
      portModal: false,
      portIndex: 0
    })
  },
  // 日期改變
  onDayPickerChange(e) {
    console.log(e.detail.value[0]);
    this.setData({
      selectedDayIndex: e.detail.value[0]
    });
  },
  onDayPickerChange2(e) {
    console.log(e.detail.value[0]);
    this.setData({
      daysIndex: e.detail.value[0]
    });
  },
  // 交通點擊
  onSelectTransport(e) {
    const id = e.currentTarget.dataset.id;
    this.setData({
      selectedTransportId: id
    });
  },
  // 時間改變
  onStartTimeChange(e) {
    const hour = this.data.hours[e.detail.value[0]];
    const minute = this.data.minutes[e.detail.value[1]];
    this.setData({
      startValue: [hour, minute],
      start_time: hour + ':' + minute + ':' + '00'
    });
    console.log('開始時間：', hour + ':' + minute);
  },

  onEndTimeChange(e) {
    const hour = this.data.hours[e.detail.value[0]];
    const minute = this.data.minutes[e.detail.value[1]];
    this.setData({
      endValue: [hour, minute],
      end_time: hour + ':' + minute + ':' + '00'
    });
    console.log('結束時間：', hour + ':' + minute);
  },
  // 點擊切換Tab
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    const user_favorite_id = e.currentTarget.dataset.user_favorite_id
    this.setData({
      user_favorite_id,
      activeIndex: index,
      scrollLeft: (index - 1) * 60 // 滾動到合適位置
    });
    this.getCollect()
  },
  timeSwitchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      timeActiveTab: tab
    });
  },

  // 滑動切換Tab
  // swiperChange(e) {
  //   const index = e.detail.current;
  //   this.setData({
  //     activeIndex: index,
  //     scrollLeft: (index - 1) * 60
  //   });
  // },


  // 初始化選擇器數據
  initPickerData() {
    // 生成 7 天日期 + 星期幾
    const days = [];
    const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const now = new Date();
    for (let i = 0; i < 7; i++) {
      const date = new Date();
      date.setDate(now.getDate() + i);
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const week = weekDays[date.getDay()];
      days.push(`${month}.${day} ${week}`);
    }

    // 小時
    const hours = [];
    for (let i = 0; i < 24; i++) {
      hours.push(i < 10 ? '0' + i : '' + i);
    }

    // 分鐘
    const minutes = [];
    for (let i = 0; i < 60; i++) {
      minutes.push(i < 10 ? '0' + i : '' + i);
    }
    console.log(days);
    this.setData({
      weekOptions: days,
      hourOptions: hours,
      minuteOptions: minutes
    });
  },

  // 選擇器滾動事件
  selectStart(e) {
    const val = e.detail.value; // [dayIndex, hourIndex, minuteIndex]
    console.log('當前選擇：',
      this.data.weekOptions[val[0]],
      this.data.hourOptions[val[1]],
      this.data.minuteOptions[val[2]]
    );
    this.setData({
      pickerValue: val
    });
  },
  selectDay(e){
    const val = e.detail.value; 
    console.log('當前選擇：',
      this.data.hourOptions[val[0]],
      this.data.minuteOptions[val[1]]
    );
    this.setData({
      dayValue: val,
    });
  },
  selectEnd(e) {
    const val = e.detail.value; // [dayIndex, hourIndex, minuteIndex]
    console.log('當前選擇：',
      this.data.weekOptions[val[0]],
      this.data.hourOptions[val[1]],
      this.data.minuteOptions[val[2]]
    );
    this.setData({
      pickerValue: val,
    });
  },
  selectTimeClick() {
    this.setData({
      timePopup: false,
      dayPopup: false
    })
  },
  // 打開彈框
  showPopup(e) {
    const childindex = e.currentTarget.dataset.childindex
    const dayindex = e.currentTarget.dataset.dayindex
    const child = e.currentTarget.dataset.child
    console.log(dayindex);
    console.log(childindex);
    console.log(child);
    this.setData({
      popupVisible: true,
      startValue: this.timeToPickerValue(child.start_time),
      endValue: this.timeToPickerValue(child.end_time),
      dayindex,
      childindex,
    });
  },
  //弹框事件转换赋值
  timeToPickerValue(timeStr) {
    if (!timeStr) return [0, 0]
    const [h, m] = timeStr.split(':')
    return [parseInt(h, 10), parseInt(m, 10)]
  },
  // 编辑弹框完成
  async editOkPopup() {
    const {
      dayindex,
      childindex,
      itineraryDetail,
      selectedTransportId
    } = this.data
    console.log(dayindex);
    console.log(childindex);
    const list_item = itineraryDetail.list_item
    list_item[dayindex].child[childindex].start_time = this.data.start_time //唯一改动游玩时间
    list_item[dayindex].child[childindex].end_time = this.data.end_time //唯一改动游玩时间
    const data = {
      "itinerary_id": itineraryDetail.info.itinerary_id,
      "itinerary_catalog_id": itineraryDetail.info.itinerary_catalog_id,
      "name": itineraryDetail.info.name,
      "number_day": itineraryDetail.info.number_day,
      "transportation": selectedTransportId, //唯一改动出行方式
      "start_time": itineraryDetail.info.start_time,
      "end_time": itineraryDetail.info.end_time,
      "img_url_cover": itineraryDetail.info.img_url_cover,
      list_item: list_item,
    }
    const res = await postUserItineraryModifyToTreeForUser(
      data
    )
    wx.showToast({
      title: '編輯成功',
    })
    this.getData()
    this.setData({
      start_time: '',
      end_time: '',
    })
    this.hidePopup()
  },
  // 编辑景点完成
  async selectPlacesOk() {
    const {
      itineraryDetail
    } = this.data;

    // 比较原始数据和现在的数据
    const original = this.originalDetail || {};
    const current = itineraryDetail;

    // 只关心 list_item 是否改动（你也可以比较整个对象）
    const isChanged = JSON.stringify(original.list_item) !== JSON.stringify(current.list_item);

    if (isChanged) {
      // 调用接口
      const data = {
        "itinerary_id": itineraryDetail.info.itinerary_id,
        "itinerary_catalog_id": itineraryDetail.info.itinerary_catalog_id,
        "name": itineraryDetail.info.name,
        "number_day": itineraryDetail.info.number_day,
        "transportation": itineraryDetail.info.transportation,
        "start_time": itineraryDetail.info.start_time,
        "end_time": itineraryDetail.info.end_time,
        "img_url_cover": itineraryDetail.info.img_url_cover,
        list_item: itineraryDetail.list_item,
      };

      await postUserItineraryModifyToTreeForUser(data);

      wx.showToast({
        title: '編輯成功',
      });

      this.setData({
        selectedDayIndex: 0,
        page: 1,
        noMore: false
      });

      this.getData();
      this.getCollect();
      this.getList(false);
    } else {
      console.log("未修改，不調用接口");
    }

    this.hidePopup();
  },
  // 關閉彈框
  hidePopup() {
    this.setData({
      popupVisible: false,
      locationVisible: false,
      selectVisible: false,
      flightVisible: false,
      trainVisible: false,
      hotelVisible: false,
      portVisible: false,
    });
  },
  // 顯示彈框
  showDeleteDialog(e) {
    const itinerary_item_id = e.currentTarget.dataset.itinerary_item_id;
    const type = e.currentTarget.dataset.type;
    const title = e.currentTarget.dataset.title;
    if (type) {
      this.setData({
        showModal: true,
        deleteName: `第${type}天行程`
      });
    }
    if (title) {
      this.setData({
        showModal: true,
        deleteName: `${title}`,
        itinerary_item_id
      });
    }
  },

  // 點擊遮罩或取消
  closeModal() {
    this.setData({
      showModal: false,
      dayModal: false,

    });
  },

  // 阻止遮罩點擊冒泡
  stopTap() {},

  // 確認刪除
  async confirmDelete() {
    const {
      itineraryDetail,
      deleteName,
      itinerary_item_id
    } = this.data;

    // 用正则取出数字
    const match = deleteName.match(/第(\d+)天/);
    if (match) {
      const dayNum = parseInt(match[1], 10); // 取出 1 并转成数字

      // 过滤掉匹配的 day_num
      itineraryDetail.list_item = itineraryDetail.list_item.filter(
        item => item.day_num !== dayNum
      );
      const data = {
        itinerary_id: itineraryDetail.info.itinerary_id,
        itinerary_catalog_id: itineraryDetail.info.itinerary_catalog_id,
        name: itineraryDetail.info.name,
        number_day: itineraryDetail.info.number_day,
        transportation: itineraryDetail.info.transportation,
        start_time: itineraryDetail.info.start_time,
        end_time: itineraryDetail.info.end_time,
        img_url_cover: itineraryDetail.info.img_url_cover,
        list_item: itineraryDetail.list_item,
      };

      // 提交接口
      const res = await postUserItineraryModifyToTreeForUser(data);
      wx.showToast({
        title: '刪除成功',
      })
      this.setData({
        showModal: false
      })
      this.getData()
      this.getCollect()
      this.getList()
    } else {
      // 遍历每一天
      itineraryDetail.list_item.forEach(day => {
        if (day.child && day.child.length) {
          // 过滤掉匹配的 itinerary_item_id
          day.child = day.child.filter(child => child.itinerary_item_id !== itinerary_item_id);
        }
      });
      console.log(itineraryDetail.list_item);
      const data = {
        itinerary_id: itineraryDetail.info.itinerary_id,
        itinerary_catalog_id: itineraryDetail.info.itinerary_catalog_id,
        name: itineraryDetail.info.name,
        number_day: itineraryDetail.info.number_day,
        transportation: itineraryDetail.info.transportation,
        start_time: itineraryDetail.info.start_time,
        end_time: itineraryDetail.info.end_time,
        img_url_cover: itineraryDetail.info.img_url_cover,
        list_item: itineraryDetail.list_item,
      };

      // 提交接口
      const res = await postUserItineraryModifyToTreeForUser(data);
      wx.showToast({
        title: '刪除成功',
      })
      this.setData({
        showModal: false
      })
      this.getData()
      this.getCollect()
      this.getList()

    }


  },


  // 子項滑動開始
  handleChildTouchStart(e) {
    this.startX = e.touches[0].clientX
  },

  // 子項滑動中
  handleChildTouchMove(e) {
    const moveX = e.touches[0].clientX
    const disX = this.startX - moveX
    const {
      dayindex,
      childindex
    } = e.currentTarget.dataset

    if (disX > 30) {
      this.setChildSwipe(dayindex, childindex, true)
    } else if (disX < -30) {
      this.setChildSwipe(dayindex, childindex, false)
    }
  },

  // 子項滑動結束
  handleChildTouchEnd(e) {
    // 可選：結束時復位判斷
  },

  handleChildTouchCancel(e) {
    // 手勢被中斷時復位
    const {
      dayindex,
      childindex
    } = e.currentTarget.dataset
    this.setChildSwipe(dayindex, childindex, false)
  },

  // 設置某個 child 的滑動狀態
  setChildSwipe(dayIndex, childIndex, status) {
    const detail = this.data.itineraryDetail

    detail.list_item.forEach((day, i) => {
      day.child.forEach((c, j) => {
        if (i === dayIndex && j === childIndex) {
          c.isTouchMove = status
        } else {
          c.isTouchMove = false // 保證同一天只有一個子項展開
        }
      })
    })

    this.setData({
      itineraryDetail: detail
    })
  },
  // --- day滑動刪除 ---
  handleTouchStart(e) {
    console.log(e);
    const index = e.currentTarget.dataset.index;
    this.startX = e.touches[0].clientX;
    this.resetSwipe();
  },
  //day
  handleTouchMove(e) {
    const moveX = e.touches[0].clientX;
    const disX = this.startX - moveX;
    const index = e.currentTarget.dataset.index;

    if (disX > 30) {
      this.setSwipe(index, true);
    } else if (disX < -30) {
      this.setSwipe(index, false);
    }
  },
  //day
  handleTouchEnd(e) {},
  //day
  handleTouchCancel() {
    this.resetSwipe();
  },

  setSwipe(index, status) {
    const days = this.data.itineraryDetail.list_item.map((item, i) => {
      return {
        ...item,
        isTouchMove: i === index ? status : false
      };
    });
    this.setData({
      'itineraryDetail.list_item': days
    });
  },

  resetSwipe() {
    const days = this.data.itineraryDetail.list_item.map(item => ({
      ...item,
      isTouchMove: false
    }));
    this.setData({
      'itineraryDetail.list_item': days
    });
  },
  back() {
    wx.reLaunch({
      url: `/pages/Itinerary/myItineraryDetails/myItineraryDetails?itinerary_id=${this.data.itineraryDetail.info.itinerary_id}`,
    })
  }
})